package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.user.Address;
import com.cskaoyan.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description: ${description}
 * @author: cuicui
 **/
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    CartMapper cartMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    SystemConfigMapper systemConfigMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;

    @Override
    public CartCheckedVO checked(CartCheckedBO bo) {
        Integer userId = getId();
        //在cart表中通过user_id、product_id修改该用户商品状态：1表示选中
        List<Integer> productIds = bo.getProductIds();
        Cart record = new Cart();
        record.setUpdateTime(new Date());
        if (bo.getIsChecked() == 1) {
            record.setChecked(true);
        } else {
            record.setChecked(false);
        }
        updateCarts(productIds, record);
        CartCheckedVO cartCheckedVO = getCartCheckedVO(userId);
        return cartCheckedVO;
    }

    private CartCheckedVO getCartCheckedVO(Integer userId) {
        //通过user_id查询该用户的购物车信息(选中的)
        CartExample example = new CartExample();
        example.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(example);
        Double checkedGoodsAmount = getAmount(carts);//选中商品总价
        //通过user_id查询该用户的购物车信息(所有的)
        CartExample example1 = new CartExample();
        example1.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<Cart> carts1 = cartMapper.selectByExample(example1);
        Double goodsAmount = getAmount(carts1);//购物车所有商品总价
        CartCheckedVO vo = new CartCheckedVO();
        CartCheckedVO.CartTotalDTO dto = new CartCheckedVO.CartTotalDTO();
        dto.setGoodsCount(carts1.size());
        dto.setCheckedGoodsCount(carts.size());
        dto.setGoodsAmount(goodsAmount);
        dto.setCheckedGoodsAmount(checkedGoodsAmount);
        vo.setCartList(carts1);
        vo.setCartTotal(dto);
        return vo;
    }

    private Integer getId() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipals().getPrimaryPrincipal();
        return user.getId();
    }

    @Override
    public CartCheckedVO delete(List<Integer> productIds) {
        Cart cart = new Cart();
        cart.setUpdateTime(new Date());
        cart.setDeleted(true);
        updateCarts(productIds, cart);
        CartCheckedVO cartCheckedVO = getCartCheckedVO(getUserId());
        return cartCheckedVO;
    }

    @Override
    public Integer fastadd(FastaddBO bo) {
        CartExample example = new CartExample();
        CartExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(getUserId()).andProductIdEqualTo(bo.getProductId());
        List<Cart> carts1 = cartMapper.selectByExample(example);
        if(carts1.size()!=0){
            Cart record = new Cart();
            record.setNumber(bo.getNumber());
            cartMapper.updateByExampleSelective(record, example);
            return carts1.get(0).getId();
        }
        Cart cart = new Cart();
        cart.setUserId(getUserId());
        cart.setGoodsId(bo.getGoodsId());
        Goods goods = goodsMapper.selectByPrimaryKey(bo.getGoodsId());
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setGoodsName(goods.getName());
        cart.setProductId(bo.getProductId());
        GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(bo.getProductId());
        cart.setPrice(goodsProduct.getPrice());
        cart.setNumber(bo.getNumber());
        cart.setSpecifications(goodsProduct.getSpecifications());
        cart.setChecked(true);
        cart.setPicUrl(goods.getPicUrl());
        cart.setAddTime(new Date());
        cart.setUpdateTime(new Date());
        cart.setDeleted(false);
        cartMapper.insertSelective(cart);
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(getUserId()).andGoodsIdEqualTo(bo.getGoodsId());
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        return carts.get(carts.size() - 1).getId();
    }

    @Override
    public CartCheckoutVO checkout(CartCheckoutBO bo) {
        Integer userId = getUserId();
        CartExample example = new CartExample();
        example.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo(false).andCheckedEqualTo(true);
        List<Cart> carts = cartMapper.selectByExample(example);
        if (bo.getCartId() != 0) {
            carts = new ArrayList<>();
            carts.add(cartMapper.selectByPrimaryKey(bo.getCartId()));
        }
        return getCartCheckoutVO(bo, userId, carts);
    }

    private CartCheckoutVO getCartCheckoutVO(CartCheckoutBO bo, Integer userId, List<Cart> carts) {
        Address address = addressMapper.selectByPrimaryKey(bo.getAddressId());
        BigDecimal couponPrice = new BigDecimal("0");
        BigDecimal goodsTotalPrice = new BigDecimal("0");
        for (int i = 0; i < carts.size(); i++) {
            goodsTotalPrice = goodsTotalPrice.add(carts.get(i).getPrice().multiply(new BigDecimal(carts.get(i).getNumber())));
        }
        if (bo.getCouponId() != -1 && bo.getCouponId() != 0 && ((goodsTotalPrice.doubleValue() - couponMapper.selectByPrimaryKey(bo.getCouponId()).getMin().doubleValue()) > 0)) {
            //使用优惠券
            couponPrice = couponMapper.selectByPrimaryKey(bo.getCouponId()).getDiscount();
        }
        BigDecimal orderTotalPrice = goodsTotalPrice.subtract(couponPrice);
        String market_express_freight_min = systemConfigMapper.selectByKeyName("market_express_freight_min");
        Integer freightPrice = 0;
        if (Integer.parseInt(market_express_freight_min) > orderTotalPrice.intValue()) {
            //有运费
            freightPrice = Integer.parseInt(systemConfigMapper.selectByKeyName("market_express_freight_value"));
        }
        BigDecimal actualPrice = orderTotalPrice.add(new BigDecimal(freightPrice));//实际价格
        //查询优惠券的数量
        Integer availableCouponLength = couponMapper.selectAccount(userId);
        //封装结果
        CartCheckoutVO vo = new CartCheckoutVO();
        vo.setCouponId(bo.getCouponId());
        vo.setGrouponRulesId(0);
        vo.setActualPrice(actualPrice);
        vo.setOrderTotalPrice(orderTotalPrice);
        vo.setCartId(bo.getCartId());
        vo.setUserCouponId(bo.getUserCouponId());
        vo.setGoodsTotalPrice(goodsTotalPrice);
        vo.setAddressId(bo.getAddressId());
        vo.setGrouponPrice(actualPrice);
        vo.setCheckedAddress(address);
        vo.setCouponPrice(couponPrice);
        vo.setAvailableCouponLength(availableCouponLength);
        vo.setFreightPrice(freightPrice);
        vo.setCheckedGoodsList(carts);
        return vo;
    }

    private Double getAmount(List<Cart> carts) {
        Double sum = 0.0;
        for (int i = 0; i < carts.size(); i++) {
            sum += carts.get(i).getPrice().doubleValue() * carts.get(i).getNumber();
        }
        return sum;
    }

    private Integer getUserId() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipals().getPrimaryPrincipal();
        return user.getId();
    }

    private void updateCarts(List<Integer> productIds, Cart cart) {
        for (int i = 0; i < productIds.size(); i++) {
            CartExample example = new CartExample();
            CartExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(getUserId()).andProductIdEqualTo(productIds.get(i));
            cartMapper.updateByExampleSelective(cart, example);
        }
    }

}
